#ifndef MYLIST_H
#define MYLIST_H

#include <esp_types.h>
#include <esp_heap_caps.h>
#include <stdlib.h>
#include <string.h>

typedef struct
{
    void **obj_p;
    size_t size;
    size_t capacity;
} general_list_t;

static inline void *object_new(size_t size)
{
    void *ret = heap_caps_malloc(size, MALLOC_CAP_SPIRAM);
    if (ret)
    {
        memset(ret, 0, size);
    }
    return ret;
}

#define general_list_new() (general_list_t *)object_new(sizeof(general_list_t))

static inline bool general_list_add(general_list_t *list, void *obj)
{
    if (!list)
    {
        return false;
    }

    if (list->size >= list->capacity)
    {
        // 扩容操作
        size_t new_capcity = list->capacity ? list->capacity * 2 : 1;
        void **new_obj_p = (void **)heap_caps_realloc(list->obj_p, new_capcity * sizeof(void *), MALLOC_CAP_SPIRAM);
        if (!new_obj_p)
        {
            return false;
        }
        list->obj_p = new_obj_p;
        list->capacity = new_capcity;
    }

    list->obj_p[list->size++] = obj;
    return true;
}

#define foreach_in_list(type, item, list)      \
    for (size_t _i = 0; _i < list->size; _i++) \
        for (type item = list->obj_p[_i]; item; item = NULL)

#endif
